﻿using HomeCloudStorageSystem.DataBase;
using HomeCloudStorageSystem.Dtos;
using HomeCloudStorageSystem.Helps;
using HomeCloudStorageSystem.Models;
using System.Data;
using System.IO;
using System.Numerics;
using System.Security;

namespace HomeCloudStorageSystem.Services
{
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext _context;
        public UserRepository(AppDbContext context)
        {
            _context = context;
        }

        public IEnumerable<User> GetUsers(string keyword)
        {
            keyword = string.IsNullOrEmpty(keyword) == true ? "" : keyword.Trim();

            if (!string.IsNullOrEmpty(keyword))
            {
                return _context.Users.Where(n => n.UserName.Contains(keyword)
                    || n.Phone.Contains(keyword)).ToList();
            }
            else
            {
                return _context.Users;
            }
        }

        public User GetUserById(int id)
        {
            return _context.Users.Where(n => n.Id == id).FirstOrDefault();
        }

        public User GetUserByUserName(string userName)
        {
            return _context.Users.Where(n => n.UserName == userName).FirstOrDefault();
        }

        public string AddUser(IFormFile file, string userNmae, string password, string phone, string avatarsUrl)
        {
            var ex = file.ContentType.Split("/").LastOrDefault();
            var fileName = Guid.NewGuid().ToString() + "." + ex;
            string filePath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            while (File.Exists(filePath))
            {
                fileName = Guid.NewGuid().ToString() + "." + ex;
                filePath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            }
            try
            {
                // 保存图片
                byte[] fileByte = ReadStreamHelp.ReadStream(file.OpenReadStream());
                // 用户头像命名规则：Guid + 图片扩展名
                using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
                {
                    fileStream.Write(fileByte, 0, fileByte.Length);
                }
                avatarsUrl += fileName;
            }
            catch
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                return "注册失败";
            }
            var transaction = _context.Database.BeginTransaction();
            try
            {
                bool userIsEmpty = _context.Users.Any();
                var userModel = new User
                {
                    UserName = userNmae,
                    Password = password,
                    Phone = phone == "string" ? "" : phone,
                    Permission = userIsEmpty == true ? "0111" : "1111",
                    Role = userIsEmpty == true ? "成员" : "户主",
                    RegisterDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    HeadImag = avatarsUrl,
                    State = 0
                };
                _context.Users.Add(userModel);
                _context.SaveChanges();
                transaction.Commit();
                transaction.Dispose();
                return "注册成功";
            }
            catch
            {
                transaction.Rollback();
                return "注册失败";
            }
        }

        public bool UserEmpty(int id)
        {
            return _context.Users.Any(n => n.Id == id);
        }

        public bool Save()
        {
            return (_context.SaveChanges() > 0);
        }
    }
}
